package com.fdw.smartexam_system.system.controller;

import com.alibaba.fastjson2.JSON;
import com.fdw.smartexam_system.system.model.Question;
import com.fdw.smartexam_system.system.model.StudentAnswer;
import com.fdw.smartexam_system.system.service.CorrectionService;
import com.fdw.smartexam_system.system.service.QuestionService;
import com.fdw.smartexam_system.system.service.StudentAnswerService;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/correction")
public class CorrectionController {

    @Autowired
    private CorrectionService correctionService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private StudentAnswerService studentAnswerService;

    @Autowired
    private OpenAiChatModel chatModel;

    private final String SysMsg = "你是一位做题助手，精通多学科知识体系和认知发展规律，能够根据题目类型、参考答案和学生答案进行精准批改，并生成学习建议，帮助学生了解自己的薄弱知识点。请严格按照以下JSON格式生成题目数据，包含以下8个核心字段：\n" +
            "{\n" +
            "  \"score\": 批改得分(100以内数字)（满分100分）,\n" +
            "  \"feedback\": \"针对学生答案的建设性反馈，使用中文，以markdown格式输出\",\n" +
            "}";


    @GetMapping("/ai/generate")
    public ResponseEntity<?> generate(@RequestParam("answerId") Long answerId) {

        StudentAnswer answer = studentAnswerService.getAnswerById(answerId);

        Question question = questionService.getQuestionById(answer.getQuestionId());
        SystemMessage systemMessage = new SystemMessage(SysMsg);
        String message = "题目内容：" + question.getQuestionContent() +
                "参考答案：" + question.getStandardAnswer() +
                "学生答案：" + answer.getAnswerContent();
        UserMessage userMessage = new UserMessage(message);
        Prompt prompt = new Prompt(List.of(systemMessage, userMessage));
        String generation = this.chatModel.call(prompt).getResult().getOutput().getContent();
        HashMap aiCorrection = JSON.parseObject(generation, HashMap.class);
        return ResponseEntity.ok(aiCorrection);
    }
}
